<template>
  <lb-layout
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <pannel-title name="电子签名">
      <div class="box">
        <vue-esign
          ref="esign"
          :width="800"
          :height="600"
          :isCrop="isCrop"
          :lineWidth="lineWidth"
          :lineColor="lineColor"
          :bgColor.sync="bgColor"
        />
      </div>

      <form-button
        class="mt10"
        cancel-text="清空画板"
        submit-text="保存签名"
        @cancel="handleReset"
        @submit="handleGenerate"
      >
      </form-button>
    </pannel-title>
  </lb-layout>
</template>

  <script>
import { savaSignature } from "@/api/esign";
import FormButton from "@/components/FormButton";
export default {
  components: { FormButton },
  data() {
    return {
      visible: true,
      lineWidth: 6,
      lineColor: "#000000",
      bgColor: "",
      resultImg: "",
      isCrop: false,
    };
  },
  methods: {
    // 初始化方法
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs.esign.reset();
      });
    },
    // 清空画板
    handleReset() {
      this.$refs.esign.reset();
    },
    // 生成照片
    handleGenerate() {
      this.$refs.esign
        .generate()
        .then((base64) => {
          //默认生成的是base64形式的图片
          console.log(this.resultImg);
          // 将生成的base64格式的图片传给父组件
          this.$emit("handleImg", base64);
          this.visible = false;

          this.resultImg = this.base64ToFile(base64, "签名.png");
          this.submit(this.resultImg);
          //   如果需要下载
          //   const a = document.createElement("a");
          //   a.href = res;
          //   a.download = "签名.png";
          //   a.click();
          //   a.remove();
        })
        .catch((err) => {
          this.$message.error(err); // 画布没有签字时会执行这里 'Not Signned'
        });
    },
    submit(file) {
      let formData = new FormData();
      formData.append("file", file);
      formData.append("token", this.$route.query.token);
      savaSignature(formData)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.handleReset();
          window.close()
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员");
        });
    },
    base64ToFile(urlData, fileName) {
      let arr = urlData.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bytes = atob(arr[1]); // 解码base64
      let n = bytes.length;
      let ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      return new File([ia], fileName, { type: mime });
    },
  },
};
</script>

  <style lang="scss">
.box {
  margin: 0 auto;
  background: #ecf0fa;
  border-radius: 3px;
  width: 100%;
  overflow: hidden;
}
</style>
